package com.xinyan.filter;

import com.alibaba.fastjson.JSON;
import com.xinyan.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StreamUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
//@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static List<String> urlList = new ArrayList<>();
    static {
        urlList.add("/sparyUsers/login");
        urlList.add("/sparyUsers/reg");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        BodyCopyHttpServletRequestWrapper bodyCopyHttpServletRequestWrapper = new BodyCopyHttpServletRequestWrapper(request);
        String requestURI = request.getRequestURI();
        log.info("=========requestURI：{}=======", requestURI);
        if (!urlList.contains(requestURI)){
            String sparyToken = request.getHeader("spray_token");
            log.info("=========获取到登录信息：{}=======", sparyToken);
            if (StringUtils.isBlank(sparyToken)) {
                R fail = R.fail(9005, "用户没有登录");
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
                ServletOutputStream outputStream = response.getOutputStream();
                StreamUtils.copy(JSON.toJSONString(fail), StandardCharsets.UTF_8, outputStream);
                return;
            }
        }


        filterChain.doFilter(request, servletResponse);
//        filterChain.doFilter(bodyCopyHttpServletRequestWrapper,servletResponse);
    }
}
